package com.googlecode.garbagecan.perf4jstudy;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class PipedIO {
	public static void main(String[]args) throws Exception {
		Sender sender = new Sender();
		Receiver receiver = new Receiver();

		PipedOutputStream out = sender.getOutputStream();
		PipedInputStream in = receiver.getInputStream();
		out.connect(in);
		
		new Thread(sender).start();
		new Thread(receiver).start();
	}
}

class Sender implements Runnable {
	private PipedOutputStream out = new PipedOutputStream();
	public PipedOutputStream getOutputStream() {
		return out;
	}
	public void run() {
		try {
			for(int i = 0; i < 10; i++) {
				String msg = "message " + i;
				out.write(msg.getBytes());
				out.flush();
				Thread.sleep(1000);
			}
			out.write("END".getBytes());
			out.flush();
			out.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

class Receiver implements Runnable {
	private PipedInputStream in = new PipedInputStream();
	public PipedInputStream getInputStream() {
		return in;
	}
	public void run() {
		byte[] bytes = new byte[1024];
		try {
			while (true) {
				int length = in.read(bytes);
				String msg = new String(bytes, 0, length);
				System.out.println(msg);
				if(msg.equals("END")) {
					break;
				}
			}
			in.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
